package com.text.textRecognition.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.ocr_api20210707.models.RecognizeGeneralResponse;
import com.aliyun.ocr_api20210707.models.RecognizeGeneralResponseBody;
import com.aliyun.tea.TeaException;
import com.text.textRecognition.service.TextRecognitionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 * <p>
 * Date: 2023-04-24
 * Time: 15:21
 * Description:
 */
@Service
@Slf4j
public class TextRecognitionServiceImpl implements TextRecognitionService {

    private static final Integer SUCCESS_CODE = 200;

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Override
    public String getRecognizeResult(MultipartFile file, HttpServletResponse httpServletResponse) {
        //参考文档 https://help.aliyun.com/document_detail/442250.htm?spm=a2c4g.442328.0.0.6e603aedSjQEVe
        try {
            //将文件转为输入流
            File temFile = File.createTempFile("temp", null);
            file.transferTo(temFile);
            InputStream bodyStream = new FileInputStream(temFile);

            com.aliyun.ocr_api20210707.Client client = createClient(accessKeyId, accessKeySecret);
            com.aliyun.ocr_api20210707.models.RecognizeGeneralRequest recognizeGeneralRequest = new com.aliyun.ocr_api20210707.models.RecognizeGeneralRequest();
            recognizeGeneralRequest.setBody(bodyStream);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            //获取结果
            RecognizeGeneralResponse response = client.recognizeGeneralWithOptions(recognizeGeneralRequest, runtime);
            log.info("文字识别结果：{}", JSON.toJSONString(response));
            Integer statusCode = response.getStatusCode();
            if (!SUCCESS_CODE.equals(statusCode)) {
                log.error("文字识别失败");
                return null;
            }
            RecognizeGeneralResponseBody body = response.getBody();
            statusCode = response.getStatusCode();
            if (!SUCCESS_CODE.equals(statusCode)) {
                log.error("文字识别失败");
                return null;
            }
            JSONObject json = (JSONObject) JSONObject.toJSON(JSON.parse(body.getData()));
            String content = json.getString("content");
            log.info("文字识别最终文字内容:{}", content);
            return content;

            //将文字转成文件导出去
            // downLoadFile(content,httpServletResponse);
        } catch (TeaException error) {
            com.aliyun.teautil.Common.assertAsString(error.message);
            log.error("文字识别失败：{}", error.message);
        } catch (Exception e) {
            TeaException error = new TeaException(e.getMessage(), e);
            com.aliyun.teautil.Common.assertAsString(error.message);
            log.error("文字识别失败：{}", error.message);
        }

        return null;
    }

    private void downLoadFile(String content, HttpServletResponse response) {
        String name = "识别结果";
        try {
            File f = new File(name + ".txt");
            FileOutputStream fos = new FileOutputStream(f);
            fos.write(content.getBytes());
            OutputStream out = response.getOutputStream();
            BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
            byte[] buf = new byte[1024];
            int len = 0;

            String fileName = name + ".txt";
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setContentType("text/plain;charset=utf-8");
            response.setCharacterEncoding("UTF-8");

            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            fos.close();
            br.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    private static com.aliyun.ocr_api20210707.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.ocr_api20210707.Client(config);
    }
}
